import { FC, useCallback, useEffect, useRef, useState } from 'react'
import { DeleteOutlined, DownloadOutlined, PaperClipOutlined } from '@ant-design/icons'
import './style.less'
import { downloadFile, getFileInfoByIds, previewImg } from '@/api/file'
import { Flex, Modal } from 'antd'
import classnames from 'classnames'
import { useImmer } from 'use-immer'

interface Props {
  ids: string | number | number[] | null
  type?: 'detail' | ''
  onDelete?: (returnIds: string | number[] | undefined, deleteId: number) => void
  children?: any
  className?: string
}
const CheckUploadFile: FC<Props> = (props: Props) => {
  const { ids, type, onDelete, children, className } = props
  const fileList = useRef<any[]>([])
  const [fileShowList, setFileShowList] = useImmer<any[]>([])
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [previewTitle, setPreviewTitle] = useState('')
  const hasInit = useRef(false)

  // 下载
  const callDownload = (item: { id: number }) => {
    downloadFile({
      file_id: item.id
    })
  }
  // 删除
  const deleteFile = (index: number) => {
    const deleteId = fileList.current[index].id
    fileList.current.splice(index, 1)
    setFileShowList((prev) => {
      prev.splice(index, 1)
    })
    const idsNum = fileList.current.map((item) => item.id)
    let returnIds: string | number[] = idsNum
    if (typeof ids === 'string') {
      returnIds = idsNum.join(',')
    } else if (Array.isArray(ids)) {
      returnIds = idsNum
    }
    hasInit.current = true
    onDelete?.(returnIds, deleteId)
  }
  // 是否是图片
  const isImg = (file: { name: string | string[] }) => {
    return file.name.includes('.jpg') || file.name.includes('.jpeg') || file.name.includes('.png')
  }
  // 获取图片url
  const getImgUrl = async (file: { id: any }) => {
    return previewImg({
      file_id: file.id
    })
  }
  // 预览
  const handlePreview = (file: { id?: number; name: any; url: any }) => {
    setPreviewImage(file.url)
    setPreviewOpen(true)
    setPreviewTitle(file.name)
  }
  const handleCancel = () => setPreviewOpen(false)
  const handleList = useCallback(() => {
    const hasImg = fileList.current.some((item) => isImg(item))
    if (hasImg && !hasInit.current) {
      fileList.current.forEach(async (item) => {
        if (isImg(item)) {
          getImgUrl(item)
            .then((res) => {
              item.url = res
              setFileShowList([...fileList.current])
            })
            .catch((error) => Promise.reject(error))
        }
      })
    } else {
      setFileShowList(fileList.current)
    }
  }, [setFileShowList])

  useEffect(() => {
    if (ids && !hasInit.current) {
      let localIds: number[] = []
      if (typeof ids === 'string') {
        localIds = ids
          .split(',')
          .filter((item) => item)
          .map((id) => +id)
      } else if (typeof ids === 'number') {
        localIds = [ids]
      } else if (Array.isArray(ids)) {
        localIds = ids
      }
      getFileInfoByIds({ ids: localIds }).then((res: any) => {
        fileList.current = res ?? []
        handleList()
      })
    }
  }, [handleList, ids])

  return (
    <>
      {!!fileShowList.length && (
        <Flex vertical gap="middle">
          {fileShowList.map((item: { id: number; name: string; url: string }, index: number) => (
            <Flex key={item.id} align="center" gap={'middle'} className={classnames(['global-check-item-file-wrapper', className])}>
              <PaperClipOutlined style={{ fontSize: 24 }} />
              {isImg(item) && (
                <div onClick={() => handlePreview(item)}>
                  <img src={item.url} alt={item.name} className="w-12 cursor-pointer" />
                </div>
              )}
              {!isImg(item) && <p>{item.name}</p>}
              {!type && <DeleteOutlined onClick={() => deleteFile(index)} style={{ fontSize: 24 }} />}
              <DownloadOutlined onClick={() => callDownload(item)} style={{ fontSize: 24 }} />
              {children}
            </Flex>
          ))}
        </Flex>
      )}
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  )
}

export default CheckUploadFile
